import asyncpg
from aiohttp import web
from aiohttp.web_request import Request
from asyncpg import Record
from asyncpg.pool import Pool

routes = web.RouteTableDef()

DB_KEY = "database"


async def create_database_pool(app):
    print("创建数据库池...")
    pool = await asyncpg.create_pool(
        host="127.0.0.1",
        port=5432,
        user="around",
        password="zhouwei",
        database="products",
        min_size=6,
        max_size=6,
    )
    app[DB_KEY] = pool


async def destroy_database_pool(app):
    print("销毁数据库连接池...")
    pool = app[DB_KEY]
    await pool.close()


@routes.get(f'/products/{id}')
async def brand(request: Request):
    try:
        # 从url中获取参数
        str_id = request.match_info["id"]
        product_id = int(str_id)

        query = """
        select product_id, product_name from product where product_id = $1;
        """

        connection = request.app[DB_KEY]
        result: Record = await connection.fetch(query, product_id)

        if result is not None:
            return web.json_response(dict(result))
        else:
            raise web.HTTPNotFound()

    except ValueError:
        raise web.HTTPBadRequest()


app = web.Application()
app.on_startup.append(create_database_pool)
app.on_cleanup.append(destroy_database_pool)
app.router.add_routes(routes)
web.run_app(app)
